<template>
  <div class="container">
    <div>
      <button id="clear">清空画布</button>
      <button id="imgInfo">保存签名</button>
    </div>
    <canvas id="canvas" width="300" height="300" />
    <div id="imgs" class="imgs" />
  </div>
</template>
<script>
export default {
  name: 'Canvas',
  components: {},
  data() {
    return {
      myCanvas: '',
      ctx: '',
      imgs: ''
    }
  },
  mounted() {
    // 1.获取canvas
    var myCanvas = document.getElementById('canvas')
    // 获取2d对象
    var ctx = myCanvas.getContext('2d')
    // 清空画布
    var clear = document.getElementById('clear')
    // 保存签名
    var imgInfo = document.getElementById('imgInfo')
    // 保存的盒子
    var imgs = document.getElementById('imgs')
    // 控制线条是否画
    var isMouseMove = false
    // 线条位置
    var lastX, lastY

    initCanvas()
    // 初始化
    function initCanvas() {
      const offset = myCanvas.getBoundingClientRect()
      var start = (e) => {
        e.preventDefault()
        isMouseMove = true
        drawLine(
          e.changedTouches[0].clientX - offset.left,
          e.changedTouches[0].clientY - offset.top,
          false
        )
      }
      const move = (e) => {
        if (isMouseMove) {
          drawLine(
            e.changedTouches[0].clientX - offset.left,
            e.changedTouches[0].clientY - offset.top,
            true
          )
        }
      }
      const end = (e) => {
        isMouseMove = false
      }
      const cancel = (e) => {
        isMouseMove = false
      }

      myCanvas.addEventListener('touchstart', start)
      myCanvas.addEventListener('touchmove', move)
      myCanvas.addEventListener('touchend', end)
      myCanvas.addEventListener('touchcancel', cancel)
    }
    // 画线
    function drawLine(x, y, isT) {
      if (isT) {
        ctx.beginPath()
        ctx.lineWidth = 2 // 设置线宽状态
        ctx.strokeStyle = 'black' // 设置线的颜色状态
        ctx.lineCap = 'round'
        ctx.lineJoin = 'round'
        ctx.moveTo(lastX, lastY)
        ctx.lineTo(x, y)
        ctx.stroke()
        ctx.closePath()
      }
      // 每次移动都要更新坐标位置
      lastX = x
      lastY = y
    }

    // 清空画图
    function clearCanvas() {
      imgs.innerHTML = ''
      ctx.beginPath()
      ctx.clearRect(0, 0, myCanvas.width, myCanvas.height)
      ctx.closePath() // 可加入，可不加入
    }
    // 保存图片
    function saveImgInfo() {
      var images = myCanvas.toDataURL('image/png')
      imgs.innerHTML = `<img src='${images}'>`
    }
    clear.addEventListener('click', clearCanvas)
    imgInfo.addEventListener('click', saveImgInfo)
  },
  methods: {
  }
}
</script>
<style scoped>
* {
	margin: 0;
	padding: 0;
}
#canvas {
	border: 1px solid black;
}
</style>
